package db.dao;


import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import bean.Articlebean;
import db.ArticleDbOpenHelper;
import utils.MyConstaints;
import utils.SPUtils;
import utils.StreamTool;
import utils.ThreadUtils;
import utils.ToastUtils;


public class ArticleDao {
	ArticleDbOpenHelper helper;

	public ArticleDao(Context context){
		helper = new ArticleDbOpenHelper(context);
	}
	//	public void update(String name, String sex){
//		
//		SQLiteDatabase db = helper.getWritableDatabase();
//		
//		db.execSQL("delete from article;");
//		db.execSQL("DELETEFROM sqlite_sequence WHERE name= 'article';");
//		db.close();
//	}
	public static ArrayList<Articlebean>  findBytype(String type,Context context){

		//获得一个可读的数据库
		SQLiteDatabase db = new ArticleDbOpenHelper(context).getReadableDatabase();
		Cursor cursor = db.query("article", new String[]{"id","title","provider","date"}, "type=?", new String[]{type}, null, null, null);
		ArrayList<Articlebean> temp=new ArrayList<Articlebean>();
		int i=0;
		while(cursor.moveToNext()){
			temp.add(new Articlebean(cursor.getInt(0), cursor.getString(1), cursor.getString(2), cursor.getString(3)));
		}
		cursor.close();
		db.close();
		return temp;
	}
	public static void update(final Context context){
		final SQLiteDatabase db = new ArticleDbOpenHelper(context).getWritableDatabase();
		String sql = "DELETE FROM   article;";
		db.execSQL(sql);
		ThreadUtils.runInThread(new Runnable() {

			@Override
			public void run() {
				try {
					String path = "http://www.cfeng8.com/Ischool/index.php/article/ajax";
					URL url = new URL(path);
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();

					conn.setRequestMethod("GET");

					conn.setConnectTimeout(2000);

					int code = conn.getResponseCode();
					if(code==200){
						InputStream in = conn.getInputStream();

						String value = StreamTool.decodeStream(in);

						JSONArray arr = new JSONArray(value);
						for (int i = 0; i < arr.length(); i++) {
							JSONObject temp = (JSONObject) arr.get(i);
							int id=temp.getInt("id");
							String title=temp.getString("title");
							String type=temp.getString("type");
							String provider=temp.getString("provider");
							String time=temp.getString("datetime").substring(0, 10);
							String sql= "insert into article values("+id
									+ ",'"+title+"'"
									+ ",'"+type+"'"
									+ ",'"+provider+"'"
									+ ",'"+time+"'"
									+ ");";
							db.execSQL(sql);
						}
						db.close();
						SPUtils.putBoolean(context, MyConstaints.UPDATED, true);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}
}
